//
//  ForViewController.m
//  JackDeve
//
//  Created by apple on 17/5/11.
//  Copyright © 2017年 wkq. All rights reserved.
//

#import "ForViewController.h"

@interface ForViewController ()<UITableViewDelegate, UITableViewDataSource,UITextFieldDelegate>
{ForView * v;
    NSDictionary * _dic;
    NSDictionary * _dic2;
}




//验证码按钮
@property (nonatomic, strong) UIButton *codeBtn;
//弹出验证码
@property (nonatomic, strong) XDCodePopView *codePopView;

//倒计时总时长
@property (nonatomic, assign) int secondsCountDown;

//定时器
@property (nonatomic, strong) NSTimer *countDownTimer;
//登录
@property (nonatomic, strong) UIButton *forGetPassWordBtn;
@end

@implementation ForViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor =[UIColor whiteColor];
    
    //创建一个添加按钮
    UIButton *navLeftBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 5, 20, 20)];
    [navLeftBtn setBackgroundImage:[UIImage imageNamed:@"左箭头"] forState:UIControlStateNormal];
    [navLeftBtn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:navLeftBtn];
    self.title =@"忘记密码";
    v =[[ForView alloc]initWithFrame:self.view.frame];
    self.view =v;
    v.table.delegate = self;
    v.table.dataSource = self;
    
}
//返回方法
-(void)click
{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellID = [NSString stringWithFormat:@"%@%ld%ld",@"XDTextFieldTableViewCellID",indexPath.section, indexPath.row];
    XDTextFieldTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        
        cell = [[XDTextFieldTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textField.secureTextEntry = NO;
    }
    
    if (indexPath.row == 0) {
        
        cell.textField.tag = 10;
        cell.textField.placeholder = @"输入手机号";
        cell.textField.leftView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon1_11"]];
        cell.textField.leftViewMode = UITextFieldViewModeAlways;
        cell.textField.keyboardType = UIKeyboardTypeNumberPad;
    }
    else if (indexPath.row == 2)
    {
        cell.textField.tag = 12;
        cell.textField.placeholder = @"输入新密码";
        cell.textField.leftView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon1_11"]];
        cell.textField.leftViewMode = UITextFieldViewModeAlways;
        //cell.textField.keyboardType = UIKeyboardTypeNumberPad;
        
    }
    else if (indexPath.row == 1)
    {
        static NSString *codeCellID = @"XDTextFeildCodeTableViewCellID";
        XDTextFeildCodeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:codeCellID];
        if (!cell) {
            
            cell = [[XDTextFeildCodeTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:codeCellID];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.textField.tag = 11;
            cell.textField.leftView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon10_03"]];
            
            cell.textField.leftViewMode = UITextFieldViewModeAlways;
            [cell.codeBtn addTarget:self action:@selector(codeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            cell.codeBtn.tag=21;
          
        }
        
        return cell;
    }
    
    
    return cell;
}


//获取验证码
- (void)codeBtnClick:(UIButton *)btn
{
    UITextField *phoneNumberTextField = [v.table viewWithTag:10];
    
    BOOL isPhoneNumber = [XDTools isMobileNumber:phoneNumberTextField.text];
    
    if (isPhoneNumber) {
        
        NSLog(@"手机号正确");
        
        [self MessageCodeHttp];
    }
    else
    {
        [self.view makeToast:@"请输入正确的手机号码" duration:0.5f position:CSToastPositionCenter];
    }
}

//获取短信验证码请求
- (void)MessageCodeHttp
{
    UITextField *phoneNumberTextField = [v.table viewWithTag:10];
    
    
    
    NSString *str = [[NSString stringWithFormat:Send2,phoneNumberTextField.text] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL * url =[NSURL URLWithString:str];
    
    NSURLSession * session =[NSURLSession sharedSession];
    //数据任务
    NSURLSessionDataTask * task =[session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        
        _dic =[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        
        [self MessageCodeHttpFinish];
        
        
    }];
    
    [task resume];
    
    
    
}

- (void)MessageCodeHttpFinish
{
    
    
    if ([[_dic objectForKey:@"errmsg"] isEqualToString:@"验证码发送成功"]) {
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            UIButton *codeBtn = [v.table viewWithTag:21];
            
            codeBtn.userInteractionEnabled = NO;
            
            codeBtn.alpha = 0.4;
            [self timer];
        });
        
        
        [self.view makeToast:@"获取短信验证码成功" duration:0.5f position:CSToastPositionCenter];
        
    }
    else
    {
        [_codePopView.contentView makeToast:[_dic objectForKey:@"ResultDesc"] duration:0.5f position:CSToastPositionCenter];
    }
}

//计时器
- (void)timer
{
    //设置倒计时总时长
    _secondsCountDown = 60;//60秒倒计时
    //开始倒计时
    _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES]; //启动倒计时后会每秒钟调用一次方法 timeFireMethod
    
    //设置倒计时显示的时间
    
    UIButton *codeBtn = [v.table viewWithTag:21];
    [codeBtn setTitle:[NSString stringWithFormat:@"已发送(%d)",_secondsCountDown] forState:UIControlStateNormal];
}

//倒计时
-(void)timeFireMethod{
    //倒计时-1
    _secondsCountDown--;
    
    UIButton *codeBtn = [v.table viewWithTag:21];
    
    //修改倒计时标签现实内容
    [codeBtn setTitle:[NSString stringWithFormat:@"已发送(%d)",_secondsCountDown] forState:UIControlStateNormal];    //当倒计时到0时，做需要的操作，比如验证码过期不能提交
    
    if(_secondsCountDown == 0){
        [_countDownTimer invalidate];
        codeBtn.userInteractionEnabled = YES;
        codeBtn.alpha = 1;
        [codeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
    }
}


- (void)textFieldDidEndEditing:(UITextField *)textField
{
    UITextField *phoneNumberTextField = [v.table viewWithTag:10];
    
    UITextField *newsPhoneNumberTextField = [v.table viewWithTag:12];
    
    if (textField == phoneNumberTextField || textField == newsPhoneNumberTextField) {
        
        BOOL isPhoneNumber = [XDTools isMobileNumber:textField.text];
        
        if (isPhoneNumber) {
            
            NSLog(@"手机号正确");
        }
        else
        {
            [self.view makeToast:@"请输入正确的手机号码" duration:0.5f position:CSToastPositionCenter];
        }
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    return YES;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return SCREEN_HEIGHT / 4;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 95 + SCREEN_HEIGHT / 16 * 2;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    XDLoginHeaderView *header = [[XDLoginHeaderView alloc]init];
    
    return header;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    XDRegisterFooderView *fooder = [[XDRegisterFooderView alloc]init];
    
    [fooder.registerBtn setTitle:@"修改密码" forState:UIControlStateNormal];
    [fooder.registerBtn addTarget:self action:@selector(registerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [fooder.loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [fooder.loginBtn addTarget:self action:@selector(registerBtnClick1) forControlEvents:UIControlEventTouchUpInside];
    return fooder;
}
//登录
- (void)registerBtnClick1{
    [self.navigationController popViewControllerAnimated:YES];
    
    
    
}

//修改按钮
- (void)registerBtnClick:(UIButton *)btn
{
    UITextField *phoneTextField = [v.table viewWithTag:10];
    
    UITextField *codeTextField = [v.table viewWithTag:11];
    
    UITextField *secore = [v.table viewWithTag:12];
    
    BOOL isPhoneNumber = [XDTools isMobileNumber:phoneTextField.text];
    
    if (isPhoneNumber) {
        
        if (codeTextField.text.length != 0) {
            [self RegisterHttpPhoneNumber:phoneTextField.text  mima:secore.text VerificationCode:codeTextField.text];
            
        }
        else
        {
            [self.view makeToast:@"输入验证码" duration:0.5f position:CSToastPositionCenter];
        }
    }
    else
    {
        [self.view makeToast:@"请输入正确的手机号码" duration:0.5f position:CSToastPositionCenter];
    }
}


//注册请求需要添加相应的验证吗和手机号码
- (void)RegisterHttpPhoneNumber:(NSString *)phoneNumber  mima:(NSString*)mimaNumber VerificationCode:(NSString *)code
{
    
    
    [[[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:[NSString stringWithFormat:Change,phoneNumber,mimaNumber,code]] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        _dic2 = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@"%@",_dic2);
        
        [self RegisterFinish];
        
    }] resume];
}

- (void)RegisterFinish
{
    if ([[_dic2 objectForKey:@"errmsg"] isEqualToString:@"手机号错误"]) {
        //验证码输入正确之后才会判断是否为存在
        NSLog(@"手机号错误");
    }
    else if ([[_dic2 objectForKey:@"errmsg"] isEqualToString:@"验证码错误"]) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertController *alet = [UIAlertController alertControllerWithTitle:@"提示" message:@"验证码输入错误" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *act1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            UIAlertAction *act2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alet addAction:act1];
            [alet addAction:act2];
            [self presentViewController:alet animated:YES completion:nil];
        });
        
    }
    
    else if([[_dic2 objectForKey:@"errmsg"] isEqualToString:@"密码修改成功"])
    {
        NSLog(@"密码修改成功");
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
            
            UIAlertController *alet = [UIAlertController alertControllerWithTitle:@"提示" message:@"修改成功" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *act1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self.navigationController popViewControllerAnimated:YES];
                
            }];
            UIAlertAction *act2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alet addAction:act1];
            [alet addAction:act2];
            [self presentViewController:alet animated:YES completion:nil];
            
            
        });
    }
    else if([[_dic2 objectForKey:@"errmsg"] isEqualToString:@"need login"]){
        
//        NSLog(@"需要登录");
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
            
            UIAlertController *alet = [UIAlertController alertControllerWithTitle:@"提示" message:@"请您登陆" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *act1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
              [self.navigationController popViewControllerAnimated:YES];
                
            }];
            UIAlertAction *act2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alet addAction:act1];
            [alet addAction:act2];
            [self presentViewController:alet animated:YES completion:nil];
            
        });
  
    }
    else{
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
            
            UIAlertController *alet = [UIAlertController alertControllerWithTitle:@"提示" message:@"修改失败" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *act1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self.navigationController popViewControllerAnimated:YES];
                
            }];
            UIAlertAction *act2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alet addAction:act1];
            [alet addAction:act2];
            [self presentViewController:alet animated:YES completion:nil];
            
            
        });
    }
    
}


@end
